package org.jeecg.modules.rest.handle;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RestUtil;
import org.springframework.web.client.HttpClientErrorException;

/**
 * 统一公共请求
 */
public class CommonRestHandle {
    /**
     * 统一封装公共类POST请求
     * @param url
     * @param paramObject
     * @return
     * @throws JeecgBootException
     */
    public JSONObject postRest(String url, JSONObject paramObject) throws JeecgBootException {
        try {
            return RestUtil.post(url, paramObject);
            //System.out.println(rspObject.toJSONString());
        }catch (HttpClientErrorException e){
            // 403 Forbidden: [{"request_id":"a047f1f1e41a9c205ef63242f62d0666"
            // ,"error":"error_auth","message":"Invalid access_token."}]
            String errMsg=e.getMessage();
            if(errMsg.contains("[{") && errMsg.contains("}]")){
                String errJsonStr = errMsg.substring(errMsg.indexOf("[{")
                        ,errMsg.indexOf("}]",errMsg.indexOf("[{"))+2  );
                JSONArray jsonArray = JSONArray.parseArray(errJsonStr);
                JSONObject o = (JSONObject) jsonArray.get(0);
                return o;
            }
            JSONObject o = new JSONObject();
            o.put("error","error");
            o.put("message",e.getMessage());
            return o;
        }
    }
    /**
     * 统一封装公共类GET请求
     * @param url
     * @param paramObject
     * @return
     * @throws Exception
     */
    public JSONObject getRest(String url,JSONObject paramObject) throws JeecgBootException {
        try {
            return RestUtil.get(url, paramObject);
        }catch (HttpClientErrorException e){
            String errMsg=e.getMessage();
            if(errMsg.contains("[{") && errMsg.contains("}]")){
                String errJsonStr = errMsg.substring(errMsg.indexOf("[{")
                        ,errMsg.indexOf("}]",errMsg.indexOf("[{"))+2  );
                JSONArray jsonArray = JSONArray.parseArray(errJsonStr);
                JSONObject o = (JSONObject) jsonArray.get(0);
                return o;
            }
            JSONObject o = new JSONObject();
            o.put("error","error");
            o.put("message",e.getMessage());
            return o;
        }
    }
}
